package com.etone.smartAudit.onlyoffice.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.etone.smartAudit.domain.Quota;
import com.etone.smartAudit.mapper.QuotaMapper;
import com.etone.smartAudit.service.QuotaService;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

@Slf4j
public class QuotaDataListener implements ReadListener<Quota> {

    /**
     * 每隔2000条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 2000;
    /**
     * 缓存的数据
     */
    private List<Quota> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private QuotaMapper quotaMapper;

    public QuotaDataListener(QuotaMapper quotaMapper) {
        this.quotaMapper = quotaMapper;
    }

    @Override
    public void invoke(Quota quota, AnalysisContext analysisContext) {
        quota.setCreateDate(new Date());
        log.info("解析到一条数据:{}", JSON.toJSON(quota));
        cachedDataList.add(quota);
        //每2000条数据存一次数据到数据库中
        if (cachedDataList.size()>=BATCH_COUNT){
            log.info("{}条数据，开始存储数据库",cachedDataList.size());
            quotaMapper.saveAll(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            log.info("成功存储数据库！");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //保存最后的数据
        quotaMapper.saveAll(cachedDataList);
        log.info("所有数据存储完毕");
    }
}
